﻿using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;
using HiTeachers.Entities;
using HiTeachers.Services;
using HiTeachers.Utilities;
using HiTeachers.Web.Payment;

namespace HiTeachers.Web
{
    public partial class Profile : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;

            if (!string.IsNullOrEmpty(Request["mbid"]))//ReAuthentication After payment.
            {
                var mbId = new Guid(Request["mbid"]);
                Teacher teacher = TeacherServices.GetById(mbId);
                if (teacher != null)
                {
                    var roles = teacher.Roles.Select(it => it.Name).ToArray();
                    var userIdentity = new GenericIdentity(teacher.Email);
                    var gp = new GenericPrincipal(userIdentity, roles);

                    HttpContext.Current.User = gp;
                    FormsAuthentication.SetAuthCookie(teacher.Email, true);
                }
                else FormsAuthentication.RedirectToLoginPage();
            }

            if (!Page.User.Identity.IsAuthenticated)
            {
                FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (string.IsNullOrEmpty(Request["order_code"]) && string.IsNullOrEmpty(Request["pmv"]))
            {
                mtvProfile.SetActiveView(vMain);
                btnUpdateAccount.Visible = !CurrentUser.Roles.Select(it => it.Name).ToList().Contains("Admin");
            }
            else
            {
                mtvProfile.SetActiveView(vPayment);
                UpdateAccountBinding();
            }
        }

        #region Toolbar Events
        protected void BtnChangePasswordClick(object sender, EventArgs e)
        {
            mtvProfile.SetActiveView(vChangePassword);
            Page.CloseMessage(lblChangePasswordMsg);
        }

        protected void BtnUpdateProfileClick(object sender, EventArgs e)
        {
            mtvProfile.SetActiveView(vDocument);
            Page.CloseMessage(lblDocumentMsg);
            BindingSubject(chklSubject);
            BindingProfile();
        }

        protected void BtnFeedbackClick(object sender, EventArgs e)
        {
            mtvProfile.SetActiveView(vFeedback);

            rptFeedback.DataSource = CurrentUser.Feedbacks;
            rptFeedback.DataBind();
        }

        protected void BtnUpdateAccountClick(object sender, EventArgs e)
        {
            mtvProfile.SetActiveView(vPayment);

            UpdateAccountBinding();
        }
        #endregion

        #region Update Information Events
        protected void BtnSaveDocClick(object sender, EventArgs e)
        {
            try
            {
                //Teacher teacher = CurrentUser;
                Teacher teacher = TeacherServices.GetById(CurrentUser.ID);

                teacher.Name = txtName.Text;
                teacher.Age = Convert.ToInt32(txtAge.Text);
                teacher.PhoneNumber = txtPhone.Text;

                teacher.Address = txtAddress.Text;
                teacher.District = txtDistrict.Text;
                teacher.City = txtCity.Text;
                teacher.Availability = txtTeachTimes.Text;
                teacher.Intro = txtIntroSumary.Text;
                teacher.Discribe = txtIntro.Text;
                teacher.Fees = Convert.ToDecimal(txtFees.Text);
                teacher.IsReceiveNews = chkReceiveNews.Checked;

                string subjects = chklSubject.Items.Cast<ListItem>().Where(item => item.Selected).Aggregate(string.Empty, (current, item) => current + (item.Value + ","));
                if (!string.IsNullOrEmpty(subjects)) subjects = subjects.Substring(0, subjects.Length - 1);
                teacher.Subject = subjects;

                if (fupFrfImage.HasFile)
                {
                    string pathFile = Server.MapPath("MemberImgs");
                    string fileName = string.Format("{0}{1}", teacher.ID, Path.GetExtension(fupFrfImage.FileName));
                    fupFrfImage.SaveAs(Path.Combine(pathFile, fileName));
                    string vtlPathFile = string.Format("/MemberImgs/{0}", fileName);

                    teacher.ImagePath = vtlPathFile;
                }

                TeacherServices.SaveOrUpdate(teacher);
                Page.DisplayMessage(lblDocumentMsg, "Cập nhật thành công!", MessageType.Success);
            }
            catch (Exception ex)
            {
                Page.DisplayMessage(lblDocumentMsg, "Cập nhật không thành công!", MessageType.Success);
                Logger.Debug(ex.Message);
            }
        }

        protected void BtnPasswordChangeClick(object sender, EventArgs e)
        {
            try
            {
                //Teacher teacher = CurrentUser;
                Teacher teacher = TeacherServices.GetById(CurrentUser.ID);

                teacher.Password = CryptorEngine.Encrypt(txtNewPassword.Text, CryptorEngine.EncryptKey, true);
                TeacherServices.SaveOrUpdate(teacher);

                SendPasswordChangedNotificationEmail(teacher, txtNewPassword.Text);
                Page.DisplayMessage(lblChangePasswordMsg, "Cập nhật thành công!", MessageType.Success);
            }
            catch (Exception ex)
            {
                Page.DisplayMessage(lblChangePasswordMsg, "Cập nhật không thành công!", MessageType.Success);
                Logger.Debug(ex.Message);
            }
        }
        #endregion

        protected void DdlPeriodSelectedIndexChanged(object sender, EventArgs e)
        {
            BindingPrice(CurrentUser);
        }

        protected void CancelClick(object sender, EventArgs e)
        {
            mtvProfile.SetActiveView(vMain);
        }

        #region Private Methods

        #region Update Info Methods
        public void SendPasswordChangedNotificationEmail(Teacher teacher, string newPassword)
        {
            string tmpPath = Server.MapPath("mailtemplates");
            string mailCntPath = Path.Combine(tmpPath, "MailContents.xml");

            var dataSet = new DataSet();
            dataSet.ReadXml(mailCntPath);
            DataRow[] rows = dataSet.Tables["PasswordChanged"].Select();
            string subject = Convert.ToString(rows[0]["Subject"]);

            NVelocityBuilder.SetResourcePath(tmpPath);
            var contentMail = NVelocityBuilder.PwChangedNotificationEmailBuilder(Convert.ToString(rows[0]["Content"]), teacher.Name, teacher.Email, newPassword);

            EmailSender.SendMail(subject, contentMail, teacher.Email);
        }

        private void BindingProfile()
        {
            Teacher teacher = TeacherServices.GetById(CurrentUser.ID);

            txtName.Text = teacher.Name;
            txtAge.Text = (teacher.Age != 0) ? teacher.Age.ToString() : string.Empty;
            txtPhone.Text = teacher.PhoneNumber;
            prfImage.ImageUrl = teacher.ImagePath;
            txtAddress.Text = teacher.Address;
            txtDistrict.Text = teacher.District;
            txtCity.Text = teacher.City;
            txtTeachTimes.Text = teacher.Availability;
            txtIntroSumary.Text = teacher.Intro;
            txtIntro.Text = teacher.Discribe;

            if (teacher.Fees == 0) chkNegotiate.Checked = true;
            else txtFees.Text = teacher.Fees.ToString("#,#.00#");

            IList<string> subjects = new List<string>(teacher.Subject.Split(','));
            foreach (ListItem item in chklSubject.Items.Cast<ListItem>().Where(item => subjects.Contains(item.Value))) item.Selected = true;
        }
        #endregion

        private void UpdateAccountBinding()
        {
            //Teacher teacher = CurrentUser;
            Teacher teacher = TeacherServices.GetById(CurrentUser.ID);

            ltrName.Text = teacher.Name;
            teacherPic.ImageUrl = teacher.ImagePath;

            string subTitles = string.Empty;
            string[] subjects = teacher.Subject.Split(',');
            subTitles = subjects.Select(subject => SubjectServices.GetById(Convert.ToInt16(subject))).Aggregate(subTitles, (current, sub) => current + (sub.Name + ", "));
            if (!string.IsNullOrEmpty(subTitles)) subTitles = subTitles.Substring(0, subTitles.Length - 2);

            ltrSubject.Text = subTitles;
            ltrAddress.Text = string.Format("{0} ,{1}, {2}", teacher.Address, teacher.District, teacher.City);
            ltrEmail.Text = teacher.Email;
            ltrPhone.Text = teacher.PhoneNumber;

            BindingPeriodDropdown();
            CheckPayment();

            BindingPrice(teacher);
        }

        private void BindingPeriodDropdown()
        {
            var lstFees = new List<FeeConfig>(FeeConfigServices.GetAll());
            lstFees.Sort((it1, it2) => it1.Period.CompareTo(it2.Period));

            ddlPeriod.DataValueField = "ID";
            ddlPeriod.DataTextField = "Name";
            ddlPeriod.DataSource = lstFees;
            ddlPeriod.DataBind();
        }

        private void BindingPrice(Teacher teacher)
        {
            FeeConfig feeConfig = FeeConfigServices.GetById(ddlPeriod.SelectedValue);
            txtPaymentFees.Text = (feeConfig.Fees != 0) ? feeConfig.Fees.ToString("#,#") : "0";

            DateTime fromDate = teacher.DeactivatedDate < DateTime.Now ? DateTime.Now : teacher.DeactivatedDate;
            DateTime toDate = fromDate.AddMonths(feeConfig.Period);

            ltrFullAccountPeriod.Text = string.Format("Từ ngày: <b style=\"color:#0375DC;\">{0}</b> đến ngày: <b style=\"color:#0375DC;\">{1}</b>",
                fromDate.ToString("dd/MM/yyyy"), toDate.ToString("dd/MM/yyyy"));

            BidingPaymentButton(feeConfig);
        }

        private void BidingPaymentButton(FeeConfig selectedFees)
        {
            if (selectedFees.Fees > 0)
            {
                //Hiển thị tổng giá tiền ở cuối trang và nơi đặt nút thanh toán
                DateTime curDaTime = DateTime.Now;
                string receiver = NlCheckout.Receiver; //Tài khoản nhận tiền 
                string price = selectedFees.Fees.ToString(); //Lấy giá của giỏ hàng
                string return_url = string.Format("{0}/Profile.aspx?mbid={1}", SiteUrl, CurrentUser.ID); // Địa chỉ trả về 
                string transaction_info = string.Format("{0}({1}) đóng phí full account cho {2}", CurrentUser.Name,
                                                        CurrentUser.Email, selectedFees.Name); //Thông tin giao dịch
                string order_code = string.Format("HTF{0}_{1,2:00}{2,2:00}{3}{4,2:00}{5,2:00}{6,2:00}",
                                                  selectedFees.Period, curDaTime.Day, curDaTime.Month, curDaTime.Year,
                                                  curDaTime.Hour, curDaTime.Minute, curDaTime.Second); //Mã giỏ hàng 

                string url = NlCheckout.BuildCheckoutUrl(return_url, receiver, transaction_info, order_code, price);
                ibtPayment.PostBackUrl = url; //Gán địa chỉ url cho nút thanh toán

                ibtPayment.Visible = true;
                btnUpgrade.Visible = false;
            }
            else
            {
                ibtPayment.Click += IbtPaymentClick;

                btnUpgrade.Visible = true;
                ibtPayment.Visible = false;
            }
        }

        protected void BtnUpgradeClick(object sender, EventArgs e)
        {
            Teacher teacher = TeacherServices.GetById(CurrentUser.ID);
            FeeConfig feeConfig = FeeConfigServices.GetById(ddlPeriod.SelectedValue);

            DateTime fromDate = teacher.DeactivatedDate < DateTime.Now ? DateTime.Now : teacher.DeactivatedDate;
            DateTime toDate = fromDate.AddMonths(feeConfig.Period);

            teacher.IsFullAccount = true;
            teacher.ActivatedDate = fromDate;
            teacher.DeactivatedDate = toDate;
            TeacherServices.SaveOrUpdate(teacher);

            Page.DisplayMessage(lblPaymentMsg,
                    "Quá trình nâng cấp thành công.", MessageType.Success);
        }

        protected void IbtPaymentClick(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            //Teacher teacher = CurrentUser;
            Teacher teacher = TeacherServices.GetById(CurrentUser.ID);
            FeeConfig feeConfig = FeeConfigServices.GetById(ddlPeriod.SelectedValue);

            DateTime fromDate = teacher.DeactivatedDate < DateTime.Now ? DateTime.Now : teacher.DeactivatedDate;
            DateTime toDate = fromDate.AddMonths(feeConfig.Period);

            teacher.IsFullAccount = true;
            teacher.ActivatedDate = fromDate;
            teacher.DeactivatedDate = toDate;
            TeacherServices.SaveOrUpdate(teacher);

            Page.DisplayMessage(lblPaymentMsg,
                    "Quá trình nâng cấp thành công.", MessageType.Success);
        }

        private void CheckPayment()
        {
            if (string.IsNullOrEmpty(Request["order_code"]))
            {
                Page.CloseMessage(lblPaymentMsg);
                return;
            }

            string transaction_info = Request.QueryString["transaction_info"];
            string order_code = Request.QueryString["order_code"];
            string payment_id = Request.QueryString["payment_id"];
            string payment_type = Request.QueryString["payment_type"];
            string secure_code = Request.QueryString["secure_code"];
            string price = Request.QueryString["price"];
            string error_text = Request.QueryString["error_text"];

            string pmPeriod = order_code.Substring(3, 1);
            FeeConfig feeConfig = FeeConfigServices.GetByPeriod(Convert.ToInt32(pmPeriod));
            if (feeConfig != null) ddlPeriod.SelectedValue = feeConfig.ID.ToString();

            bool check = NlCheckout.VerifyPaymentUrl(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code);
            if (check)
            {
                //Teacher teacher = CurrentUser;
                Teacher teacher = TeacherServices.GetById(CurrentUser.ID);
                //if ("1".Equals(payment_type))//Thanh toan ngay|2:Thanh toan tam giu.
                //{
                DateTime fromDate = teacher.DeactivatedDate < DateTime.Now ? DateTime.Now : teacher.DeactivatedDate;
                DateTime toDate = fromDate.AddMonths(Convert.ToInt32(pmPeriod));

                teacher.IsFullAccount = true;
                teacher.ActivatedDate = fromDate;
                teacher.DeactivatedDate = toDate;
                TeacherServices.SaveOrUpdate(teacher);

                //TODO:Send Email to user
                NlCheckout.SendNotityPaymentEmail(teacher, price, DateTime.Now);
                //}

                var paymentInfo = new PaymentInfo
                                              {
                                                  OrderCode = order_code,
                                                  OrderInfo = transaction_info,
                                                  PaymentId = payment_id,
                                                  Price = price,
                                                  Period = Convert.ToInt32(pmPeriod),
                                                  Status = "1".Equals("payment_type") ? PaymentStatus.Success : PaymentStatus.Pending,
                                                  Teacher = teacher
                                              };
                PaymentInfoServices.SaveOrUpdate(paymentInfo);

                Page.DisplayMessage(lblPaymentMsg,
                    "Quá trình thanh toán thành công.", MessageType.Success);
            }
            else
                Page.DisplayMessage(lblPaymentMsg, "Quá trình thanh toán thất bại. Bạn vui lòng thử lại", MessageType.Error);
        }

        #endregion
    }
}
